package ynu.edu.achitecturework.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ynu.edu.achitecturework.dao.DeviceDAO;
import ynu.edu.achitecturework.dao.SensorDataDAO;
import ynu.edu.achitecturework.entity.Device;
import ynu.edu.achitecturework.entity.SensorData;

import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class DeviceService {

    private final DeviceDAO deviceDAO;
    private final SensorDataDAO sensorDataDAO;
    private final DataCollectionService dataCollectionService;

    public List<Device> getAllDevices() {
        return deviceDAO.findAll();
    }

    @Transactional(readOnly = true)
    public List<Device> getDevicesByGreenhouse(Long greenhouseId) {
        log.debug("查询大棚 {} 的设备列表", greenhouseId);
        return deviceDAO.findByGreenhouseId(greenhouseId);
    }

    public List<SensorData> getRecentSensorData(Long deviceId) {
        // 先收集新数据
        dataCollectionService.collectSensorData("300023040198");
        // 然后返回最近7次的数据
        return sensorDataDAO.findTop7ByDeviceIdOrderByCreateTimeDesc(deviceId);
    }
    public SensorData getLatestSensorData(Long deviceId) {
        // 先收集新数据
        dataCollectionService.collectSensorData("300023040198");
        // 返回最新的一条数据
        return sensorDataDAO.findTopByDeviceIdOrderByCreateTimeDesc(deviceId);
    }
}